package com.abel.bigwater.dataserver.model.ewide

import com.abel.bigwater.data.BcdString
import io.netty.buffer.ByteBuf
import java.util.*

class KmingSpecifyData(_pduLen: Int = -1) : TermData(KmingDataType.ReqSpecificData, _pduLen) {
    var channel: KmingChannelType? = KmingChannelType.AllChannel

    var startTimeStr: BcdString? = null

    var endTimeStr: BcdString? = null

    var startTime: Date?
        get() = startTimeStr?.toFullYearTime()
        set(value) {
            startTimeStr = if (value == null) null else fromFullYearTime(value)
        }

    var endTime: Date?
        get() = endTimeStr?.toFullYearTime()
        set(value) {
            endTimeStr = if (value == null) null else fromFullYearTime(value)
        }

    override fun bufLength() = 1 + 1 + 7 + 7

    override fun parseBuf(buf: ByteBuf): Boolean {
        assert(type == KmingDataType.findByCode(buf.readUnsignedByte()))

        channel = KmingChannelType.findByCode(buf.readUnsignedByte())
        startTimeStr = BcdString.create(buf, 7)
        endTimeStr = BcdString.create(buf, 7)

        return true
    }

    override fun pack(buf: ByteBuf) {
        buf.alloc().buffer().apply {
            writeByte(type.code.toInt())
            writeByte(channel!!.code.toInt())

            startTime
            writeBytes(startTimeStr!!.hexArray)

            endTime
            writeBytes(endTimeStr!!.hexArray)

            buf.writeBytes(this)
        }
    }
}